// Created by wangliang on 2025/3/14.
import 'package:flutter/material.dart';

class ExpandableText extends StatefulWidget {
  final String text;
  final TextStyle? style;
  final int maxLines;
  final String expandText;
  final String collapseText;
  final Color expandCollapseColor;
  final double maxWidth;

  const ExpandableText({
    Key? key,
    required this.text,
    this.style,
    this.maxLines = 3,
    this.expandText = '展开',
    this.collapseText = '收起',
    this.expandCollapseColor = const Color(0xff2B91D0),
    required this.maxWidth
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() => _ExpandableTextState();
}

class _ExpandableTextState extends State<ExpandableText> {
  bool isExpanded = false;
  bool isOverflow = false;
  late Size _lastSize;

  @override
  void initState() {
    super.initState();
    _lastSize = Size.zero;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _checkOverflow();
    });
  }

  @override
  void didUpdateWidget(covariant ExpandableText oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.text != widget.text) {
      _checkOverflow();
    }
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final newSize = MediaQuery.of(context).size;
    if (newSize != _lastSize) {
      _lastSize = newSize;
      _checkOverflow();
    }
  }

  void _checkOverflow() {
    final textPainter = TextPainter(
      text: TextSpan(text: widget.text, style: widget.style),
      maxLines: widget.maxLines,
      textDirection: TextDirection.ltr,
    );
    textPainter.layout(maxWidth: widget.maxWidth);
    setState(() {
      isOverflow = textPainter.didExceedMaxLines;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          widget.text,
          maxLines: isExpanded ? null : widget.maxLines,
          overflow: isExpanded ? TextOverflow.visible : TextOverflow.clip,
          style: widget.style,
        ),
        if (isOverflow)
          GestureDetector(
            onTap: () {
              setState(() {
                isExpanded = !isExpanded;
              });
            },
            child: Text(
              isExpanded ? widget.collapseText : widget.expandText,
              style: TextStyle(color: widget.expandCollapseColor),
            ),
          ),
      ],
    );
  }
}